package cn.imatu.framework.mock.data.generator;

import cn.imatu.framework.mock.data.model.MysqlTableColumn;
import cn.imatu.framework.tool.core.StringUtils;
import cn.hutool.core.util.StrUtil;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author shenguangyang
 */
public class MockHelper {
    @Resource
    private ApplicationContext applicationContext;
    private static MockDataRule mockDataRule;

    @PostConstruct
    public void init() {
        mockDataRule = applicationContext.getBean(MockDataRule.class);
    }

    public static String mock(MysqlTableColumn column) {
        Map<Supplier<String>, String[]> ruleData = mockDataRule.ruleData();
        for (Map.Entry<Supplier<String>, String[]> entry : ruleData.entrySet()) {
            String columnComment = column.getColumnComment();
            String columnKey = column.getColumnKey();
            List<String> regList = Arrays.stream(entry.getValue()).map(x -> "*" + x + "*").collect(Collectors.toList());
            if (StringUtils.matches(columnComment, regList, true) ||
                    StringUtils.matches(columnKey, regList, true)) {
                return entry.getKey().get();
            } else if (StrUtil.containsAnyIgnoreCase(columnComment, entry.getValue()) ||
                    StrUtil.containsAnyIgnoreCase(columnKey, entry.getValue())) {
                return entry.getKey().get();
            }
        }
        return "1";
    }
}
